#include "ChessTimer.h"
#include <iostream>

using namespace std;

ChessTimer::ChessTimer()
{
	running = false;
	elapsed = 0.0;
	myduration = 0.0;
}

void ChessTimer::setTime(double duration)
{
	myduration = duration;
}

void ChessTimer::start()
{
	if (!running)
	{
		mystart = MYGETTIME();
		running = true;
	}
}

void ChessTimer::stop()
{
	if (running)
	{
		myend = MYGETTIME();
		running = false;
		elapsed = MYSECONDS(myend - mystart);
		if (elapsed < 0.0)
		{//print it to both streams so it is harder to have not show up
			cerr << "TIMER ERROR: negative elapsed time!" << endl;
			cout << "TIMER ERROR: negative elapsed time!" << endl;
		}
		myduration -= elapsed;
		if (myduration < 0.0)
		{//ditto
			cerr << "Time duration used up!" << endl;
			cout << "Time duration used up!" << endl;
		}
	}
}

double ChessTimer::timeLeft()
{
	if (running)
	{
		return myduration - MYSECONDS(MYGETTIME() - mystart);
	} else {
		return myduration;
	}
}

double ChessTimer::timeElapsed()
{
	if (running)
	{
		return MYSECONDS(MYGETTIME() - mystart);
	} else {
		return elapsed;
	}
}

bool ChessTimer::isRunning()
{
	return running;
}
